package com.logjun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.logjun.reggie.common.R;
import com.logjun.reggie.dto.DishDto;
import com.logjun.reggie.entity.Category;
import com.logjun.reggie.entity.Dish;
import com.logjun.reggie.entity.DishFlavor;
import com.logjun.reggie.entity.Employee;
import com.logjun.reggie.service.CategoryService;
import com.logjun.reggie.service.DishFlavorService;
import com.logjun.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    DishService dishService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishFlavorService dishFlavorService;

    /**
     * 菜品分页信息查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "dishCache",key = "'dishPage'+#page+'_'+#pageSize+'_'+#name")
    public R paeg(int page, int pageSize, String name) {
        log.info("开始查询......");
        //构造分页查询器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        lambdaQueryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo,lambdaQueryWrapper);
        //将查询结果封装进新的page对象，作为返回数据
        BeanUtils.copyProperties(pageInfo,dishPage,"records");
        List<Dish> records = pageInfo.getRecords();
        //遍历records，把records里的dish对象转换成dishDto对象
        List<DishDto> dtoList = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //复制dish对象
            BeanUtils.copyProperties(item, dishDto);
            //根据dish中的categoryId查询数据库中的分类名字段
            Category category = categoryService.getById(item.getCategoryId());
            //是否为空
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        //将新的records对象赋给dishPage
        dishPage.setRecords(dtoList);
        return R.success(dishPage);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto){
        log.info("菜品信息：{}",dishDto.toString());
        //两步新增，第一保存数据道菜品表吗，第二保存口味数据到菜品口味
        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功");
    }

    /**
     * 根据id查询对应的菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable(value = "dishCache",key = "'dish'+#id")
    public R<DishDto> get(@PathVariable Long id){
        //创建需要回传的DishDto实体，需要查询多表
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 更新操作
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("需要更新的数据：{}",dishDto.toString());
        dishService.updateByIdWithFlavor(dishDto);
        return R.success("菜品更新成功");
    }

    /*@GetMapping("/list")
    public R list(Long categoryId){
        log.info("开始根据分类查询菜品信息...");
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/

    /**
     * 根据id或名字查询菜品信息
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "'dish_categoryId'+#dish.getCategoryId()+'_'+#dish.getName()")
    public R list(Dish dish){
        log.info("开始根据分类查询菜品信息...");
        //构造条件查询器，根据传递的参数是分类id或菜品名字查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(dish.getName()),Dish::getName,dish.getName());
        queryWrapper.eq(null != dish.getCategoryId(),Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(queryWrapper);
        //将list中的dish对象转换成dishDto对象
        List<DishDto> dishDtos = list.stream().map(item ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //根据id查分类名
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null){
                dishDto.setCategoryName(category.getName());
            }
            //查询口味信息
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,item.getId());
            dishDto.setFlavors(dishFlavorService.list(queryWrapper1));
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtos);
    }

    /**
     * 根据id删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true ,beforeInvocation = false)
    public R<String> delete(@RequestParam List<Long> ids){
        //删除前需查询关联信息，若菜品绑定了套餐则不能删除
        for (Long id : ids) {
            dishService.delete(id);
        }
        return R.success("删除菜品成功");
    }

    /**
     更新菜品状态
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> updateStatus(@RequestParam List<Long> ids,@PathVariable Integer status){
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            //如果当前菜品关联了套餐则不能更改状态
            dishService.updateWithStatus(dish);
        }
        if (status == 1){
           return R.success("已起售");
        }
        return R.success("已停售");

    }

}
